package srv

import (
	dbModel "back/entity/model"
	"back/entity/nailEntity"
	"back/entity/nailRepo"
	requset "back/router/request"
	"github.com/redis/go-redis/v9"
	"gorm.io/gen"
	"utilx/dbx/cache"
)

type NailProduct struct {
	Repo   nailRepo.NailRepo
	bucket cache.RedisBucket
	redis  *redis.Client
}

func NewProduct(repo nailRepo.NailRepo, bucket cache.RedisBucket) NailProduct {
	client := bucket.GetClient(1)
	return NailProduct{repo, bucket, client}
}
func (c NailProduct) CacheSearchById(force bool, id int64) (any, error) {
	return cache.GetAop[nailEntity.NailProduct](force, c.redis, dbModel.RedisKey(dbModel.TypeProduct, id), func() (any, error) {
		return c.SearchById(id)
	})
}
func (c NailProduct) CacheSearchBy(force bool, rec requset.SearchWithPage[nailEntity.NailProduct]) (any, error) {
	return cache.GetAop[requset.PageResult[nailEntity.NailProduct]](force, c.redis, dbModel.RedisKey(dbModel.TypeProduct, rec), func() (any, error) {
		return c.SearchBy(rec)
	})

}

func (c NailProduct) SearchById(id int64) (*nailEntity.NailProduct, error) {
	return c.Repo.NailProduct.Where(nailRepo.NailProduct.ID.Eq(id)).First()
}
func (c NailProduct) SearchBy(rec requset.SearchWithPage[nailEntity.NailProduct]) (requset.PageResult[nailEntity.NailProduct], error) {
	do := c.Repo.NailProduct.Debug()
	do = do.Where(nailRepo.NailProduct.Name.Like("%" + rec.Data.Name + "%"))
	byPage, i, err := do.FindByPage(int(rec.PageInfo.PageSize)*int(rec.PageInfo.Page-1), int(rec.PageInfo.PageSize))
	return requset.PageResult[nailEntity.NailProduct]{
		Items: byPage,
		Total: i,
	}, err
}
func (c NailProduct) DelById(id int64) (gen.ResultInfo, error) {

	return c.Repo.NailProduct.Where(nailRepo.NailProduct.ID.Eq(id)).Delete()
}
func (c NailProduct) UpdateById(rec nailEntity.NailProduct) error {

	return c.Repo.NailProduct.Where(nailRepo.NailProduct.ID.Eq(rec.ID)).Save(&rec)
}
func (c NailProduct) UpdateBy(rec requset.UpdateBy[nailEntity.NailProduct, nailEntity.NailProduct]) error {

	return c.Repo.NailProduct.Where(nailRepo.NailProduct.ID.Eq(rec.Where.ID)).Save(&rec.Target)
}
func (c NailProduct) Create(rec nailEntity.NailProduct) error {
	return c.Repo.NailProduct.Create(&rec)
}
func (c NailProduct) TopUp(rec nailEntity.NailStorageRecord) error {
	err := c.Repo.NailStorageRecord.Create(&rec)
	if err != nil {
		return err
	}
	_, err = c.Repo.NailProduct.Where(nailRepo.NailProduct.ID.Eq(rec.ID)).UpdateColumnSimple(
		nailRepo.NailProduct.Quantity.Add(rec.Quantity),
	)
	if err != nil {
		return err
	}
	return nil
}
